package com.roadmap.repo.db;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.roadmap.common.BaseConst;
import com.roadmap.common.RdcLogger;

/** Proxool is a third party for managing database connections */
public class SessionPool {
	private final static Logger logger = RdcLogger.getLogger(SessionPool.class);
	/** in the whole application there should be only one pool instance */
	private static SessionPool poolInstance;
	/** a factory which creates sessions */
	private SessionFactory sessionFactory;
	/** a lock object for synchronizing */
	private final static Object lock = new Object();

	private SessionPool() {
		try {
			Configuration config = new Configuration();
			config.configure(BaseConst.REPOSITORY_HIBENATE_FILE);
			sessionFactory = config.buildSessionFactory();
		} catch (HibernateException ex) {
			logger.fatal("fail to initialize the connection pool", ex);
			// if fail to initialise the pool, then the program exits.
			System.exit(0);
		}
	}

	/** get the pool instance */
	public static SessionPool getInstance() {
		/*
		 * ensure at any time there's only one thread to access below codes and
		 * only one pool instance is created
		 */
		synchronized (lock) {
			if (poolInstance == null)
				try {
					poolInstance = new SessionPool();
				} catch (Exception sce) {
					logger.fatal("failed to initialize the session pool", sce);
				}
		}
		return poolInstance;
	}

	/** get a session connecting to database */
	public Session getSession() {
		return sessionFactory.openSession();
	}
}
